<template>
    <div class="cate-tree">
        <el-tree
            :data="cateData"
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick"
            unselectable="on"
            :expand-on-click-node="false"
            :default-expanded-keys="defaultExpandedKeys"
            :indent="36"
            @node-contextmenu="showContextMenu"
        >
            <div
                class="tree-node"
                :class="{ active: activeNodeId == node.id }"
                slot-scope="{ node, data }"
            >
                {{ data.name }}
            </div>
        </el-tree>
        <ul
            class="context-menu"
            v-if="menuVisible"
            :style="{ left: menuX + 'px', top: menuY + 'px' }"
        >
            <li v-for="(item, index) in menuList" :key="index" @click="menuHandler(item.handler)">
                {{ item.name }}
            </li>
        </ul>
        <!-- 添加/编辑 start -->
        <el-dialog
            :title="newModalTitle"
            :visible.sync="newModalVisible"
            width="400px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            destroy-on-close
        >
            <el-form ref="newForm" :model="newForm" label-width="120px">
                <el-form-item
                    label="分类名称："
                    prop="name"
                    :rules="[
                        { required: true, message: '请输入分类名称', trigger: 'change' },
                        { validator: checkLength },
                    ]"
                >
                    <el-input
                        placeholder="请输入"
                        type="text"
                        v-model.trim="newForm.name"
                    ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button type="cancel" @click="newModalVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    :loading="adding"
                    @click="submitAction"
                    :disabled="!$store.getters.hasEditPermission"
                    >确定</el-button
                >
            </div>
        </el-dialog>
        <!-- 添加/编辑 end -->
    </div>
</template>
<script>
export default {
    data() {
        function checkLength(rule, value, callback) {
            if (value.length > 4) {
                return callback(new Error("名称不能超过4个字"))
            } else {
                callback()
            }
        }
        return {
            checkLength,
            activeCata: 0,
            cateData: [],
            defaultExpandedKeys: [0],
            defaultProps: {
                children: "children",
                label: "name",
            },
            activeNodeId: "",
            activeNode: null,
            activeData: null,
            // activeOrgNames:[],
            menuList: [],
            menuVisible: false,
            menuX: 0,
            menuY: 0,
            newModalTitle: "新建分类",
            newModalVisible: false,
            newForm: {},
            adding: false,
        }
    },
    props: {
        cateList: {
            type: Array,
            default() {
                return []
            },
            required: true,
        },
    },
    watch: {
        cateList() {
            this.initCate()
        },
    },
    created() {
        this.initCate()
    },
    mounted() {
        document.addEventListener("click", this.clickDom, false)
    },
    destroyed() {
        document.removeEventListener("click", this.clickDom, false)
    },
    methods: {
        initCate() {
            if (this.cateList.length == 0) return
            this.cateData = [
                {
                    id: 0,
                    name: "全部分类",
                    children: this.cateList,
                },
            ]
        },
        handleNodeClick(data, node, n) {
            this.activeNodeId = node.id
            this.$emit("nodeClick", data, node.level)
        },
        showContextMenu(event, data, node, el) {
            this.menuList = []
            if (this.$store.getters.hasEditPermission) {
                if (node.data.id == "0") {
                    if (this.hasPermission("030001")) {
                        this.menuList.push({
                            name: "新建分类",
                            handler: "new",
                        })
                    }
                } else {
                    if (this.hasPermission("030002")) {
                        this.menuList.push({
                            name: "编辑",
                            handler: "edit",
                        })
                    }
                    if (this.hasPermission("030003")) {
                        this.menuList.push({
                            name: "删除",
                            handler: "delete",
                        })
                    }
                }
            }

            if (this.menuList.length == 0) return
            let nodeId = node.id
            this.activeNode = node
            this.activeData = node.data
            this.menuVisible = true
            this.menuX = event.clientX
            this.menuY = event.clientY
        },
        menuHandler(type) {
            this.menuVisible = false
            if (type == "new") {
                this.newCate()
            } else if (type == "edit") {
                this.editCate()
            } else if (type == "delete") {
                this.deleteCate()
            }
        },
        hideMenu() {
            this.menuVisible = false
            // this.activeNode = null
        },
        clickDom() {
            this.hideMenu()
        },
        newCate() {
            this.newModalTitle = "新建分类"
            this.newForm = {}
            this.newForm.pid = this.activeData.id
            this.newModalVisible = true
            if (this.$refs["newForm"]) {
                this.$refs["newForm"].resetFields()
            }
        },
        editCate() {
            this.newModalTitle = "编辑分类"
            this.newForm = {
                id: this.activeData.id,
                name: this.activeData.name,
                des: this.activeData.des,
            }
            this.newModalVisible = true
        },
        deleteCate() {
            this.showConfirm("确定删除该分类吗？", () => {
                this.deleting = true
                this.$post("/noticeAnnouncement/noticeAnnouncement/delTextType", {
                    id: this.activeData.id,
                }).then(
                    (res) => {
                        this.deleting = false
                        this.$message.success("删除成功")
                        this.removeNode(this.activeNode, this.activeData)
                        this.$emit("update")
                    },
                    (err) => {
                        this.deleting = false
                        this.$message.error(err.msg)
                    }
                )
            })
        },
        removeNode(node, data) {
            const parent = node.parent
            const children = parent.data.children
            const index = children.findIndex((d) => d.id === data.id)
            children.splice(index, 1)
        },
        submitAction() {
            this.$refs["newForm"].validate((valid) => {
                if (valid) {
                    this.adding = true
                    let params = Object.assign({}, this.newForm)
                    this.$ajax({
                        url: "noticeAnnouncement/noticeAnnouncement/addOrUpdateTextType",
                        method: "post",
                        data: params,
                    }).then(
                        (data) => {
                            this.adding = false
                            this.$message.success("保存成功")
                            this.newModalVisible = false
                            this.$emit("update")
                        },
                        (error) => {
                            this.adding = false
                            this.$message.error(error.msg)
                        }
                    )
                } else {
                    return false
                }
            })
        },
    },
}
</script>
